package com.mySampleApplication.server;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.db.Db;
import cn.hutool.db.DbUtil;
import cn.hutool.db.Entity;
import cn.hutool.db.ds.DSFactory;
import cn.hutool.db.handler.EntityHandler;
import cn.hutool.db.handler.EntityListHandler;
import cn.hutool.db.sql.SqlExecutor;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.mySampleApplication.client.CodeRuleAtter.CodeRuleAtterDto;
import com.mySampleApplication.client.codeRule.CodeRuleDto;
import com.mySampleApplication.client.codeRule.CodeRuleService;
import com.smartgwt.client.widgets.grid.ListGridRecord;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * 编码规则
 */
public class CodeRuleServlet extends RemoteServiceServlet implements CodeRuleService {

    @Override
    public String getMessage(Map<String, String> record, List<Map<String, String>> list, Map<String , String> map) {

//        CodeRuleDto data = CodeRuleServlet.getSelectMap(msg);
        Encoder encoder = new Encoder(record.get("qz"), record.get("hz"), record.get("fgf"));
//        CodeRuleAtterDto dataAtter = CodeRuleAtterServlet.getSelectById(record.getAttribute("id"));
//        List<Map<String, String>> list = dataAtter.getKeyValueMap();
        list.forEach(a->{
            //流水号
            if(a.get("fdlx").equals("1")){


                // 从数据库中读取最大流水号
                long maxSerialNumberFromDatabase = 0;// 从数据库中获取最大流水号的逻辑
                if(maxSerialNumberFromDatabase!=0){
                    // 初始化流水号生成器
                    SerialNumberGenerators.initializeSerialNumber(maxSerialNumberFromDatabase);
                }
                String serialNumber = SerialNumberGenerators.getNextSerialNumber(Integer.parseInt(a.get("lshcd")), a.get("lshgs"), Integer.parseInt(a.get("lshbc")));
                encoder.addSegment(serialNumber);
            }//日期值
            else if(a.get("fdlx").equals("2")){
                LocalDate currentDate = LocalDate.now();
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
                String formattedDate = currentDate.format(formatter);
                encoder.addSegment(formattedDate);
            }//固定值
            else if(a.get("fdlx").equals("3")){
                encoder.addSegment(a.get("gdz"));
            }//字段值
            else if(a.get("fdlx").equals("4")){
                encoder.addSegment(map.get(a.get("zdsxm")));
            }
        });
        String encoded = encoder.encode();
        return encoded;
    }

    /**
     * 查询总数
     * @param map 条件
     */
    public String getTotal(Map<String, String> map) {
        String total="0";
        StringBuffer str = new StringBuffer();
        DataSource ds = DSFactory.get("mysql");
        Db.use(ds);
        Connection conn = null;
        try {
            if(map.size()>0 && !map.isEmpty()){
                map.forEach((k,v)->{
                    if(map.size()==1){
                        str.append(k).append(" like").append("'%"+v+"%'");
                    }else if (map.size()>1){
                        str.append(" and ").append(k).append(" like ").append("'%"+v+"%'");
                    }

                });
            }
            conn = ds.getConnection();
            String sql="select * from code_rule";
            if(!str.toString().equals("")){
                sql=sql+" where " +str.toString();
            }
            List<Entity> totalList = SqlExecutor.query(conn, sql, new EntityListHandler());
            total=totalList.get(0).get("total").toString();
        } catch (SQLException e) {

        } finally {
            DbUtil.close(conn);
        }
        return total;
    }

    /**
     * 查询list
     * @param map 条件
     * @param mapPage 分页
     */
    public CodeRuleDto getSelect(Map<String, String> map, Map<String, String> mapPage) {
        Map<String, List<Map>> reMap = new HashMap<>();
        CodeRuleDto dto =new CodeRuleDto();
        int pageSize =(Integer.parseInt (mapPage.get("pageSize"))-1)*Integer.parseInt (mapPage.get("pageNumber"));
        int pageNumber = Integer.parseInt (mapPage.get("pageNumber"));
        StringBuffer str = new StringBuffer();
        DataSource ds = DSFactory.get("mysql");
        Db.use(ds);
        Connection conn = null;
        try {
            if(map.size()>0 && !map.isEmpty()){
                map.forEach((k,v)->{
                    if(map.size()==1){
                        if(k.equals("db_model_id")){
                            str.append(k).append(" = ").append("'"+v+"'");
                        }else{
                            str.append(k).append(" like ").append("'%"+v+"%'");
                        }
                    }else if (map.size()>1){
                        if(str.length()==0){
                            if(k.equals("db_model_id")){
                                str.append(k).append(" = ").append("'"+v+"'");
                            }else{
                                str.append(k).append(" like ").append("'%"+v+"%'");
                            }
                        }else{
                            if(k.equals("db_model_id")){
                                str.append(" and ").append(k).append(" = ").append("'"+v+"'");
                            }else{
                                str.append(" and ").append(k).append(" like ").append("'%"+v+"%'");
                            }
                        }
                    }

                });
            }
            conn = ds.getConnection();
            String sql="select * from code_rule";
            if(!str.toString().equals("")){
                sql=sql+" where " +str.toString();
            }
            //List<Entity> totalList = SqlExecutor.query(conn, sql, new EntityListHandler());
            List<Entity> entityList = SqlExecutor.query(conn, sql+ " limit " +pageSize+","+pageNumber, new EntityListHandler());

            //reMap.put("totalData", BeanUtil.copyToList(totalList, Map.class));
            reMap.put("entityList",BeanUtil.copyToList(entityList, Map.class));
            List<Map<String,String>> list =new ArrayList<>();
            Map<String, String> mapp;
            for (Map  a:BeanUtil.copyToList(entityList, Map.class)) {
                mapp= new HashMap<>();
                Map<String, String> finalMapp = mapp;
                a.forEach((k, v)->{
//                    if(k.equals("db_model_id")){
//                        Map<String, String> data=getSelectModById(String.valueOf(v),"bt_data_object");
//                        finalMapp.put("db_model_mc",data.get("name_cn")) ;
//                    }
                    finalMapp.put(String.valueOf(k),v==null?"":v+"") ;
                });
                list.add(finalMapp);
            }
            dto.setKeyValueMap(list);
        } catch (SQLException e) {

        } finally {
            DbUtil.close(conn);
        }
        return dto;
    }

    /**
     * 查询list
     * @param id 条件
     * @param mapPage 分页
     */
    public CodeRuleDto getSelectVs(String id , Map<String, String> mapPage) {
        Map<String, List<Map>> reMap = new HashMap<>();
        CodeRuleDto dto =new CodeRuleDto();
        int pageSize =(Integer.parseInt (mapPage.get("pageSize"))-1)*Integer.parseInt (mapPage.get("pageNumber"));
        int pageNumber = Integer.parseInt (mapPage.get("pageNumber"));
        StringBuffer str = new StringBuffer();
        DataSource ds = DSFactory.get("mysql");
        Db.use(ds);
        Connection conn = null;
        try {

            conn = ds.getConnection();
            String sql="select * from code_rule_version where id='"+id+"'";

            //List<Entity> totalList = SqlExecutor.query(conn, sql, new EntityListHandler());
            List<Entity> entityList = SqlExecutor.query(conn, sql+ " limit " +pageSize+","+pageNumber, new EntityListHandler());

            //reMap.put("totalData", BeanUtil.copyToList(totalList, Map.class));
            reMap.put("entityList",BeanUtil.copyToList(entityList, Map.class));
            List<Map<String,String>> list =new ArrayList<>();
            Map<String, String> mapp;
            for (Map  a:BeanUtil.copyToList(entityList, Map.class)) {
                mapp= new HashMap<>();
                Map<String, String> finalMapp = mapp;
                a.forEach((k, v)->{
                    if(k.equals("db_model_id")){
                        Map<String, String> data=getSelectModById(String.valueOf(v),"bt_data_object");
                        finalMapp.put("db_model_mc",data.get("name_cn")) ;
                    }
                    finalMapp.put(String.valueOf(k),v==null?"":v+"") ;
                });
                list.add(finalMapp);
            }
            dto.setKeyValueMap(list);
        } catch (SQLException e) {

        } finally {
            DbUtil.close(conn);
        }
        return dto;
    }

    /**
     * 根据对象id查询数据
     */
    public static CodeRuleDto getSelectMap(String objectId) {
        Map<String, List<Map>> reMap = new HashMap<>();
        CodeRuleDto dto =new CodeRuleDto();
        StringBuffer str = new StringBuffer();
        DataSource ds = DSFactory.get("mysql");
        Db.use(ds);
        Connection conn = null;
        try {

            conn = ds.getConnection();
            String sql="select * from code_rule where db_model_id='"+objectId+"'  ";

            Entity entityList = SqlExecutor.query(conn, sql, new EntityHandler());
            Map<String, String> mapp=new HashMap<>();
            BeanUtil.beanToMap(entityList).forEach((k, v)->{
                mapp.put(String.valueOf(k),v==null?"":v+"") ;
            });

            dto.setMap(mapp);
        } catch (SQLException e) {

        } finally {
            DbUtil.close(conn);
        }
        return dto;
    }

    /**
     * 根据对象id查询数据
     */
    public CodeRuleDto getCodeRuleVersionMap(Map<String, String> map) {
        Map<String, List<Map>> reMap = new HashMap<>();
        CodeRuleDto dto =new CodeRuleDto();
        StringBuffer str = new StringBuffer();
        DataSource ds = DSFactory.get("mysql");
        Db.use(ds);
        Connection conn = null;
        try {

            conn = ds.getConnection();
            String sql="select * from code_rule_version where id='"+map.get("id")+"'  and  bb='"+map.get("bb")+"'";

            Entity entityList = SqlExecutor.query(conn, sql, new EntityHandler());
            Map<String, String> mapp=new HashMap<>();
            BeanUtil.beanToMap(entityList).forEach((k, v)->{
                mapp.put(String.valueOf(k),v==null?"":v+"") ;
            });

            dto.setMap(mapp);
        } catch (SQLException e) {

        } finally {
            DbUtil.close(conn);
        }
        return dto;
    }

    /**
     * 根据对象id查询数据
     */
    public  CodeRuleDto getCodeRuleAtterVersionMapList(Map<String, String> map) {
        Map<String, List<Map>> reMap = new HashMap<>();
        CodeRuleDto dto =new CodeRuleDto();
        StringBuffer str = new StringBuffer();
        DataSource ds = DSFactory.get("mysql");
        Db.use(ds);
        Connection conn = null;
        try {
            conn = ds.getConnection();
            String sql="select * from code_rule_atter_version where bb='"+map.get("bb")+"'  and  coderule_id='"+map.get("coderule_id")+"'";
            List<Entity> entityList = SqlExecutor.query(conn, sql, new EntityListHandler());
            reMap.put("entityList",BeanUtil.copyToList(entityList, Map.class));
            List<Map<String,String>> list =new ArrayList<>();
            Map<String, String> mapp;
            for (Map  a:BeanUtil.copyToList(entityList, Map.class)) {
                mapp= new HashMap<>();
                Map<String, String> finalMapp = mapp;
                a.forEach((k, v)->{
                    finalMapp.put(String.valueOf(k),v==null?"":v+"") ;
                });
                list.add(finalMapp);
            }
            dto.setKeyValueMap(list);
        } catch (SQLException e) {

        } finally {
            DbUtil.close(conn);
        }
        return dto;
    }

    /**
     * 插入数据
     * @param map 数据对象
     * @return
     */
    public  String setInsert(Map<String, String> map) {
        map.entrySet().removeIf(entry -> StrUtil.isBlank(entry.getValue()));
        DataSource ds = DSFactory.get("mysql");
        int i = 0;
        Db.use(ds);
        Connection conn = null;
        try {
            conn = ds.getConnection();
            StringBuffer str = new StringBuffer();
            StringBuffer value = new StringBuffer();
            str.append("(");
            value.append("(");
            map.forEach((k, v) -> {
                str.append(k).append(",");
                //value.append(v).append(",");
                value.append(v==null?v:"'"+v+"'").append(",");
            });
            str.replace(str.length() - 1, str.length(), ")");
            value.replace(value.length() - 1, value.length(), ")");
            // 插入语句
            SqlExecutor.execute(conn, "insert into code_rule " + str.toString() + " value " + value.toString() + "");
            i = 1;
        } catch (SQLException e) {
            i = 0;
        } finally {
            DbUtil.close(conn);
        }
        return String.valueOf(i);
    }

    public  String setSbInsert(Map<String, String> map) {
        map.entrySet().removeIf(entry -> StrUtil.isBlank(entry.getValue()));
        map.put("status","禁用");
        DataSource ds = DSFactory.get("mysql");
        int i = 0;
        Db.use(ds);
        Connection conn = null;
        try {
            conn = ds.getConnection();
            StringBuffer str = new StringBuffer();
            StringBuffer value = new StringBuffer();
            str.append("(");
            value.append("(");
            map.forEach((k, v) -> {
                str.append(k).append(",");
                //value.append(v).append(",");
                value.append(v==null?v:"'"+v+"'").append(",");
            });
            str.replace(str.length() - 1, str.length(), ")");
            value.replace(value.length() - 1, value.length(), ")");
            // 插入语句
            SqlExecutor.execute(conn, "insert into code_rule_version" + str.toString() + " value " + value.toString() + "");
            i = 1;
        } catch (SQLException e) {
            i = 0;
        } finally {
            DbUtil.close(conn);
        }
        return String.valueOf(i);
    }

    /**
     * 修改数据
     * @param map 数据对象
     * @return
     */
    public  String setUpdate(Map<String, String> map) {
        map.entrySet().removeIf(entry -> StrUtil.isBlank(entry.getValue()));
        DataSource ds = DSFactory.get("mysql");
        int i = 0;
        Db.use(ds);
        Connection conn = null;
        try {
            conn = ds.getConnection();
            StringBuffer str = new StringBuffer();
            StringBuffer where = new StringBuffer();
            str.append("update code_rule set ");
            where.append(" WHERE id=");
            map.forEach((k, v) -> {
                if (!k.equals("id")) {
                    str.append(k).append("=").append("'").append(v).append("'").append(",");
                } else {
                    where.append("'").append(v).append("'");
                }
            });
            str.replace(str.length() - 1, str.length(), " ");
            String sql = str.toString() + where.toString();
            // 更新语句
            SqlExecutor.execute(conn, sql);
            i = 1;
        } catch (SQLException e) {
            i = 0;
        } finally {
            DbUtil.close(conn);
        }
        return String.valueOf(i);
    }


    public static  Map<String, String> getSelectByIdMap(String id) {
        Map<String, String> mapp=new HashMap<>();
        DataSource ds = DSFactory.get("mysql");
        Db.use(ds);
        Connection conn = null;
        try {

            conn = ds.getConnection();
            String sql="select * from code_rule where id="+id;

            Entity entityList = SqlExecutor.query(conn, sql, new EntityHandler());

            BeanUtil.beanToMap(entityList).forEach((k, v)->{
                mapp.put(String.valueOf(k),v==null?"":v+"") ;
            });

        } catch (SQLException e) {

        } finally {
            DbUtil.close(conn);
        }
        return mapp;
    }

    public   Map<String, String> selectById(String id) {
        Map<String, String> mapp=new HashMap<>();
        DataSource ds = DSFactory.get("mysql");
        Db.use(ds);
        Connection conn = null;
        try {
            conn = ds.getConnection();
            String sql="select * from code_rule where id='"+id+"'";
            Entity entityList = SqlExecutor.query(conn, sql, new EntityHandler());
            BeanUtil.beanToMap(entityList).forEach((k, v)->{
                mapp.put(String.valueOf(k),v==null?"":v+"") ;
            });
        } catch (SQLException e) {
        } finally {
            DbUtil.close(conn);
        }
        return mapp;
    }

    /**
     * 升版数据
     * @param map 数据对象
     * @return
     */
    public  String setSbUpdate(Map<String, String> map) {
        map.entrySet().removeIf(entry -> StrUtil.isBlank(entry.getValue()));
        Map<String, String> ydata = getSelectByIdMap(map.get("id"));
        String timeStr1= LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        ydata.put("update_time",timeStr1);
        setSbInsert(ydata);
        CodeRuleAtterDto datc = CodeRuleAtterServlet.getSelectById(map.get("id"));
        datc.getKeyValueMap().forEach(a->{
            String timeStr2= LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            a.put("update_time",timeStr2);
            CodeRuleAtterServlet.setSbInsert(a);
        });
        Map<String, String> reMap = new HashMap<>();
        reMap.put("coderule_id",map.get("id"));
        reMap.put("bb",map.get("bb"));
        CodeRuleAtterServlet.setSbUpdate(reMap);
        DataSource ds = DSFactory.get("mysql");
        int i = 0;
        Db.use(ds);
        Connection conn = null;
        try {
            conn = ds.getConnection();
            StringBuffer str = new StringBuffer();
            StringBuffer where = new StringBuffer();
            str.append("update code_rule set ");
            where.append(" WHERE id=");
            map.forEach((k, v) -> {
                if (!k.equals("id")) {
                    str.append(k).append("=").append("'").append(v==null?"":v).append("'").append(",");
                } else {
                    where.append(v);
                }
            });
            str.replace(str.length() - 1, str.length(), " ");
            String sql = str.toString() + where.toString();
            // 更新语句
//            SqlExecutor.execute(conn, sql);
            i = 1;
        } catch (SQLException e) {
            i = 0;
        } finally {
            DbUtil.close(conn);
        }
        return String.valueOf(i);
    }


    /**
     * 修改状态数据
     * @param map 数据对象
     * @return
     */
    public  String setStatus(Map<String, String> map) {
        DataSource ds = DSFactory.get("mysql");
        int i = 0;
        Db.use(ds);
        Connection conn = null;
        try {
            conn = ds.getConnection();
            StringBuffer str = new StringBuffer();
            StringBuffer where = new StringBuffer();
            str.append("UPDATE code_rule SET `fbzt` =");
            where.append(" WHERE id=");
            map.forEach((k, v) -> {
                if (!k.equals("id")) {
                    str.append("'").append(v).append("'");
                } else {
                    where.append("'").append(v).append("'");
                }
            });
            str.replace(str.length(), str.length(), " ");
            String sql = str.toString() + where.toString();
            // 更新语句
            SqlExecutor.execute(conn, sql);
            i = 1;
        } catch (SQLException e) {
            i = 0;
        } finally {
            DbUtil.close(conn);
        }
        return String.valueOf(i);
    }




    /**
     * 批量删除数据
     * @param ids
     * @return
     */
    public  String setDelete(int[] ids) {
        DataSource ds = DSFactory.get("mysql");
        int i = 0;
        Db.use(ds);
        Connection conn = null;
        try {
            conn = ds.getConnection();
            Connection finalConn = conn;
            Arrays.stream(ids).forEach(a -> {
                // 删除语句
                try {
                    SqlExecutor.execute(finalConn, "delete from code_rule  where id=" + a);
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            });
            i = 1;
        } catch (SQLException e) {
            i = 0;
        } finally {
            DbUtil.close(conn);
        }
        return String.valueOf(i);
    }

    /**
     * 删除数据
     * @param id
     * @return
     */
    public  String deleteById(String id) {
        DataSource ds = DSFactory.get("mysql");
        int i = 0;
        Db.use(ds);
        Connection conn = null;
        try {
            conn = ds.getConnection();
            Connection finalConn = conn;
//            Arrays.stream(ids).forEach(a -> {
            // 删除语句
            try {
                SqlExecutor.execute(finalConn, "delete from code_rule  where id='" + id+"'");
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
//            });
            i = 1;
        } catch (SQLException e) {
            i = 0;
        } finally {
            DbUtil.close(conn);
        }
        return String.valueOf(i);
    }

    /**
     * 删除数据
     * @return
     */
    public  String deleteCodeRuleVersion(Map<String, String> map) {
        DataSource ds = DSFactory.get("mysql");
        deleteCodeRuleAtterVersion(map);
        int i = 0;
        Db.use(ds);
        Connection conn = null;
        try {
            conn = ds.getConnection();
            Connection finalConn = conn;
//            Arrays.stream(ids).forEach(a -> {
            // 删除语句
            try {
                SqlExecutor.execute(finalConn, "delete from code_rule_version  where id='"+map.get("id")+"'");
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
//            });
            i = 1;
        } catch (SQLException e) {
            i = 0;
        } finally {
            DbUtil.close(conn);
        }
        return String.valueOf(i);
    }


    /**
     * 删除数据
     * @return
     */
    public  String deleteCodeRuleAtterVersion(Map<String, String> map) {
        DataSource ds = DSFactory.get("mysql");
        int i = 0;
        Db.use(ds);
        Connection conn = null;
        try {
            conn = ds.getConnection();
            Connection finalConn = conn;
//            Arrays.stream(ids).forEach(a -> {
            // 删除语句
            try {
                SqlExecutor.execute(finalConn, "delete from code_rule_atter_version  where coderule_id='"+map.get("coderule_id")+"'");
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
//            });
            i = 1;
        } catch (SQLException e) {
            i = 0;
        } finally {
            DbUtil.close(conn);
        }
        return String.valueOf(i);
    }

    /**
     * 根据数据对象id获取数据对象
     * @param id
     * @param object 对象表
     * @return
     */
    public static   Map<String, String> getSelectModById(String id, String object){
        StringBuffer str = new StringBuffer();
        DataSource ds = DSFactory.get("mysql_dmp");
        Db.use(ds);
        Connection conn = null;
        Map<String, String> mapp= new HashMap<>();
        try {
            conn = ds.getConnection();
            String sql="select * from "+object+" where id="+"'"+id+"'";

            Entity entityList = SqlExecutor.query(conn, sql, new EntityHandler());

            List<Map<String,String>> list =new ArrayList<>();

            BeanUtil.beanToMap(entityList).forEach((k, v)->{
                mapp.put(String.valueOf(k),v==null?"":v+"") ;
            });


        } catch (SQLException e) {

        } finally {
            DbUtil.close(conn);
        }
        return mapp;
    }
}
